package cn.iocoder.yudao.module.system.service.datascope;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.system.controller.admin.datascope.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.datascope.DataScopeDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.system.dal.mysql.datascope.DataScopeMapper;

import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 权限范围 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class DataScopeServiceImpl implements DataScopeService {

    @Resource
    private DataScopeMapper dataScopeMapper;

    @Override
    public Long createDataScope(DataScopeSaveReqVO createReqVO) {
        // 插入
        DataScopeDO dataScope = BeanUtils.toBean(createReqVO, DataScopeDO.class);
        dataScopeMapper.insert(dataScope);
        // 返回
        return dataScope.getId();
    }

    @Override
    public void updateDataScope(DataScopeSaveReqVO updateReqVO) {
        // 校验存在
        validateDataScopeExists(updateReqVO.getId());
        // 更新
        DataScopeDO updateObj = BeanUtils.toBean(updateReqVO, DataScopeDO.class);
        dataScopeMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataScope(Long id) {
        // 校验存在
        validateDataScopeExists(id);
        // 删除
        dataScopeMapper.deleteById(id);
    }

    private void validateDataScopeExists(Long id) {
        if (dataScopeMapper.selectById(id) == null) {
            throw exception(DATA_SCOPE_NOT_EXISTS);
        }
    }

    @Override
    public DataScopeDO getDataScope(Long id) {
        return dataScopeMapper.selectById(id);
    }

    @Override
    public PageResult<DataScopeDO> getDataScopePage(DataScopePageReqVO pageReqVO) {
        return dataScopeMapper.selectPage(pageReqVO);
    }

}